function queryCtrl($scope,$rootScope,$modal) {
    $scope.editor = createTextFiled($scope);

    $scope.setting = {
        data : {
            simpleData : {
                enable : true,
                idKey : "id",
                pIdKey : "pId",
                rootPId : 0
            }
        },
        callback : {
            beforeClick : zTreeBeforeClick
        }
    };


    queryHistorySqlLog($scope,$rootScope);
    $scope.executeSql = function () {
        executeOneSql($scope,$rootScope);
    }

    $scope.executeQuery = function ($scope,sql) {
        dataQuery($scope, 0, sql);
    }

    $scope.showOneSql = function(sqlLog){
        var old = $scope.editor.getDoc().getValue();
        var newValue = old+"\n\n"+sqlLog.sqlContent;

        $scope.editor.getDoc().setValue(newValue);
        $scope.editor.refresh();
    }

    //打开SQL模版选择页
    $scope.open_box_sql_template_select = function(){
        readSqlTemplateList($scope);
        var count = 100;
       var _c = setInterval(function(){
           if(!$scope.zNodes){
               if(--count<0){
                   clearInterval(_c);
                   alert('请重试');
               }
               return;
           }
           var $modalInstance = $modal.open({
               templateUrl: 'views/sql_template_select_page.html',
               controller: Query_ModalCtrl,
               scope: $scope
           });
           clearInterval(_c);
       },100);
    }


    //小平专用sql
    $scope.show_xpzy_sql = function(){
        var old = $scope.editor.getDoc().getValue();
        var newValue = old+"\n\n"+"SELECT TABLE_SCHEMA,(sum(DATA_LENGTH)+sum(INDEX_LENGTH))/1024/1024/1024 FROM information_schema.TABLES group by TABLE_SCHEMA ORDER BY (sum(DATA_LENGTH)+sum(INDEX_LENGTH)) DESC;";

        $scope.editor.getDoc().setValue(newValue);
        $scope.editor.refresh();
    }
}

//防止重复创建CodeMirror
function createTextFiled($scope){
    if($scope.editor){
        return;
    }
    var codeMirror = CodeMirror.fromTextArea(document.getElementById("sqlArea"), {
        mode: {name: "text/x-mysql"},
        lineNumbers: true,
        styleActiveLine: true,
        lineWrapping: true,
        extraKeys: {"Ctrl": "autocomplete"}//输入s然后ctrl就可以弹出选择项
//        theme: "ambiance"//主题
    });
    codeMirror.on("keyup", function (cm, event) {
        if ((event.keyCode == 13 && event.shiftKey) || (event.keyCode == 13 && event.metaKey ))
        {
            $scope.executeSql();
            return;
        }
    });
    return codeMirror;
}
var currNode
function zTreeBeforeClick(event,node,treeId){
    currNode = node;
}

function readSqlTemplateList($scope){
    if($scope.zNodes){
        return;
    }
    $.ajax({
        url: '/db/doReadSqlTemplate',
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                $scope.$apply(function () {
                    $scope.sqlTemplateList = responseObj.dataList;
                    $.each($scope.sqlTemplateList,function(i,v){
                        v.pId = v.parentId;
                        v.t = v.content;
                        v.open = v.name=='常用SQL'|| v.name=='SQL';
                    })
                    $scope.zNodes = $scope.sqlTemplateList;
                });
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}
function Query_ModalCtrl($scope, $modalInstance) {

    //更新操作
    $scope.selectTemplate = function () {
        if($.trim(currNode.t)==''){
            alert('节点无效,请重新选择');
            return;
        }

        var old = $scope.editor.getDoc().getValue();
        var newValue = old+"\n\n"+currNode.t;
        $scope.editor.getDoc().setValue(newValue);
        $scope.editor.refresh();
        $modalInstance.close();
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
};





function executeOneSql($scope,$rootScope){
    var editor = $scope.editor;
    var currDbId = $rootScope.currDbId;//当前库Id
    var currSchemaName = $rootScope.currSchemaName//当前schema

    if(currDbId==''||currSchemaName==''){
        alert('请选择Schema');
        return;
    }
    var sql = $.trim(editor.getSelections());
    if(sql==''){
        sql = $.trim(editor.getValue());
    }
    if(sql==''){
        alert('请输入SQL');
        return;
    }
    //替换掉非法'；'以及多余的';'
    sql = sql.replace(new RegExp("；",'gm'),';').replace(new RegExp(";+",'gm'),';');

    //删除注释部分\\,--
    var arr = sql.split('\n');
    for(var i=0;i<arr.length;i++){
        var line = $.trim(arr[i]);
        if(line.substring(0,2)=='--'){
            arr[i]='';
        }else if(line.indexOf('\\\\')!=-1){
            arr[i] = line.substring(0,line.indexOf('\\\\'));
        }else if(line.indexOf('//')!=-1){
            arr[i] = line.substring(0,line.indexOf('//'));
        }
    }
    sql = arr.join(' ');
    if($.trim(sql)==''){
        alert('请输入有效Sql');
        return;
    }
    var count = countChar(sql,";");
    if(count>1){
        alert('暂不支持多字段查询');
        return;
    }
    sql = sql.replace(';','');
    dataQuery($scope,$rootScope, '', sql);
}
function countChar(str,ch){
    var re = new RegExp(ch,"g");
    if(str.match(re)){
        return str.match(re).length;
    }
    return 0;
}

function queryHistorySqlLog($scope,$rootScope){
    $.ajax({
        url: '/query/doReadHistorySqlLog',
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                $scope.$apply(function () {
                    $rootScope.sourceSqlLogList = responseObj.historySqlLog;
                    $rootScope.showSqlLogList = responseObj.historySqlLog;
                });
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function dataQuery($scope,$rootScope, pageNo, sql) {
    if (!pageNo || pageNo == 0) {
        pageNo = 1;
    }
    if (!sql || $.trim(sql) == '') {
        return;
    }

    var paramObj = new Object();
    paramObj.pageNo = pageNo;
    paramObj.pageSize = 1000;
    paramObj.dbId = $rootScope.currDbId;
    paramObj.dbName = $rootScope.currDbName;
    paramObj.schemaName = $rootScope.currSchemaName;
    paramObj.sql = sql;

    $.ajax({
        type:'post',
        url: '/query/doQueryObjectList',
        data: paramObj,
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                $scope.$apply(function () {
                    //分页数据
                    /*$scope.dataList = responseObj.data.dataList.dataList;
                    if(!$scope.dataList){
                        //如果不是分页，则取这个数据

                    }*/
                    $scope.dataList = responseObj.data.dataList

                    $scope.columns = responseObj.data.columns;
                    $scope.explain_dataList = responseObj.data.explain_dataList;
                    $scope.explain_columns = responseObj.data.explain_columns;

                    //显示相应的历史Sql
                    $rootScope.sourceSqlLogList = responseObj.historySqlLog;
                    var arr = new Array();
                    for(var i=0;i<$rootScope.sourceSqlLogList.length;i++){
                        var sqlLog = $rootScope.sourceSqlLogList[i];
                        if(sqlLog.schemaName==$rootScope.currSchemaName){
                            arr.push(sqlLog);
                        }
                    }
                    $rootScope.showSqlLogList = arr;

                });
            } else {
                alert(responseObj.errorMsg);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}



angular
    .module('inspinia')
    .controller('queryCtrl', queryCtrl)